import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:intl/intl.dart';
import 'package:family_app/src/features/finance/models/transaction_model.dart';
import 'package:family_app/src/theme/app_theme.dart';

/// 添加交易对话框
class AddTransactionDialog extends StatefulWidget {
  final String title;
  final String submitButtonText;
  final int? initialAmount;
  final TransactionType? initialType;
  final String? initialCategory;
  final String? initialDescription;
  final DateTime? initialDate;
  final Function(int amount, TransactionType type, String category,
      String? description, DateTime date) onSubmit;

  const AddTransactionDialog({
    Key? key,
    this.title = '添加交易',
    this.submitButtonText = '添加',
    this.initialAmount,
    this.initialType,
    this.initialCategory,
    this.initialDescription,
    this.initialDate,
    required this.onSubmit,
  }) : super(key: key);

  @override
  State<AddTransactionDialog> createState() => _AddTransactionDialogState();
}

class _AddTransactionDialogState extends State<AddTransactionDialog> {
  late TextEditingController _amountController;
  late TextEditingController _descriptionController;
  late TransactionType _selectedType;
  late String _selectedCategory;
  late DateTime _selectedDate;
  bool _isAmountValid = true;

  @override
  void initState() {
    super.initState();
    _amountController = TextEditingController(
      text: widget.initialAmount != null
          ? widget.initialAmount!.toString()
          : '',
    );
    _descriptionController =
        TextEditingController(text: widget.initialDescription ?? '');
    _selectedType = widget.initialType ?? TransactionType.expense;
    _selectedCategory = widget.initialCategory ??
        (_selectedType == TransactionType.expense
            ? TransactionCategories.expenseCategories.first
            : TransactionCategories.incomeCategories.first);
    _selectedDate = widget.initialDate ?? DateTime.now();
  }

  @override
  void dispose() {
    _amountController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16.r)),
      child: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.all(16.r),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              // 标题
              Text(
                widget.title,
                style: TextStyle(fontSize: 18.sp, fontWeight: FontWeight.bold),
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 24.h),

              // 金额输入
              TextField(
                controller: _amountController,
                keyboardType:
                    const TextInputType.numberWithOptions(decimal: true),
                decoration: InputDecoration(
                  labelText: '金额',
                  hintText: '请输入金额',
                  prefixIcon: const Icon(Icons.attach_money),
                  errorText: _isAmountValid
                      ? null
                      : '请输入有效金额',
                ),
                inputFormatters: [
                  FilteringTextInputFormatter.allow(RegExp(r'^\d+\.?\d{0,2}')),
                ],
                onChanged: (value) {
                  setState(() {
                    _isAmountValid = value.isNotEmpty &&
                        double.tryParse(value) != null &&
                        double.parse(value) > 0;
                  });
                },
                autofocus: true,
              ),
              SizedBox(height: 16.h),

              // 交易类型选择
              Row(
                children: [
                  Text('类型:', style: TextStyle(fontSize: 16.sp)),
                  SizedBox(width: 16.w),
                  _buildTypeSelector(),
                ],
              ),
              SizedBox(height: 16.h),

              // 分类选择
              Row(
                children: [
                  Text('分类:', style: TextStyle(fontSize: 16.sp)),
                  SizedBox(width: 16.w),
                  Expanded(child: _buildCategorySelector()),
                ],
              ),
              SizedBox(height: 16.h),

              // 日期选择
              InkWell(
                onTap: _selectDate,
                child: InputDecorator(
                  decoration: const InputDecoration(
                    labelText: '日期',
                    prefixIcon: Icon(Icons.calendar_today),
                  ),
                  child: Text(
                    DateFormat('yyyy-MM-dd').format(_selectedDate),
                    style: TextStyle(fontSize: 16.sp),
                  ),
                ),
              ),
              SizedBox(height: 16.h),

              // 备注输入
              TextField(
                controller: _descriptionController,
                decoration: const InputDecoration(
                  labelText: '备注(可选)',
                  hintText: '请输入备注',
                  prefixIcon: Icon(Icons.description),
                ),
                maxLines: 2,
              ),
              SizedBox(height: 24.h),

              // 按钮
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(),
                    child: const Text('取消'),
                  ),
                  SizedBox(width: 16.w),
                  ElevatedButton(
                    onPressed: _submitTransaction,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: AppTheme.primaryColor,
                      foregroundColor: Colors.white,
                    ),
                    child: Text(widget.submitButtonText),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建类型选择器
  Widget _buildTypeSelector() {
    return SegmentedButton<TransactionType>(
      segments: const [
        ButtonSegment<TransactionType>(
          value: TransactionType.expense,
          label: Text('支出'),
          icon: Icon(Icons.arrow_downward),
        ),
        ButtonSegment<TransactionType>(
          value: TransactionType.income,
          label: Text('收入'),
          icon: Icon(Icons.arrow_upward),
        ),
      ],
      selected: {_selectedType},
      onSelectionChanged: (Set<TransactionType> selected) {
        setState(() {
          _selectedType = selected.first;
          // 切换类型时更新分类选择
          _selectedCategory = _selectedType == TransactionType.expense
              ? TransactionCategories.expenseCategories.first
              : TransactionCategories.incomeCategories.first;
        });
      },
    );
  }

  /// 构建分类选择器
  Widget _buildCategorySelector() {
    final categories = _selectedType == TransactionType.expense
        ? TransactionCategories.expenseCategories
        : TransactionCategories.incomeCategories;

    return DropdownButton<String>(
      value: _selectedCategory,
      isExpanded: true,
      icon: const Icon(Icons.arrow_drop_down),
      elevation: 16,
      underline: Container(height: 2, color: AppTheme.primaryColor),
      onChanged: (String? value) {
        if (value != null) {
          setState(() {
            _selectedCategory = value;
          });
        }
      },
      items: categories.map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Row(
            children: [
              Icon(
                TransactionCategories.getCategoryIcon(value),
                color: AppTheme.primaryColor,
                size: 20.r,
              ),
              SizedBox(width: 8.w),
              Text(value),
            ],
          ),
        );
      }).toList(),
    );
  }

  /// 选择日期
  Future<void> _selectDate() async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate,
      firstDate: DateTime(2000),
      lastDate: DateTime.now().add(const Duration(days: 1)),
    );
    if (picked != null && picked != _selectedDate) {
      setState(() {
        _selectedDate = picked;
      });
    }
  }

  /// 提交交易
  void _submitTransaction() {
    // 验证金额
    final amountText = _amountController.text.trim();
    if (amountText.isEmpty ||
        double.tryParse(amountText) == null ||
        double.parse(amountText) <= 0) {
      setState(() {
        _isAmountValid = false;
      });
      return;
    }

    // 转换金额为分（整数）
    final amount = (double.parse(amountText) * 100).round();
    final description = _descriptionController.text.trim();

    widget.onSubmit(
      amount,
      _selectedType,
      _selectedCategory,
      description.isNotEmpty ? description : null,
      _selectedDate,
    );
  }
}
